﻿using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Model.Core;
using Models;
using SIE.SCADA.Common.Log;
using SIE.SCADA.Helper;
using SIE.SCADA.SqlSugar;
using SIE.SCADA.ZemtDemo;
using SIE.SCADA.ZemtDemo.Common;
using SIE.SCADA.ZemtDemo.MqClient.Model;

namespace SCADA_DAQ.ZEMT.Server
{
    /// <summary>
    /// 上报工时
    /// </summary>
    public class PlanManager : MqMangerBase<PlanManager>
    {
        //private smdc_disid_t _Disid_T;
        public string line_names = Env.LineName.Value;
        public string LineGroupName = Env.LineGroupName.Value;
        private readonly string IfaceName = "PRODUCTREPORT"; //接口名称
        private readonly string EXCHANAGE = "ZEMT_MQ_EXCHANGE_PRODUCTREPORT";
        private readonly string ROUTEKEY = "PRODUCTREPORT_SIE";
        private AdvancedThread thread;

        //修改状态，请求上传配置信息
        public void CheckUpload(List<smdc_disid_t> smdc_disids)
        {

            //var upload = smdc_disids.FirstOrDefault();
            //_Disid_T = upload;
            foreach (var upload in smdc_disids)
            {


                if (upload != null)
                {
                    System.TimeSpan t1 = (System.TimeSpan)(System.DateTime.Now - upload.modifytime_dt);
                    double timespan2 = 0;
                    if (t1 != null) {
                        timespan2= t1.TotalSeconds;
                    }
                    ;
                    if (timespan2 > 120) {
                        List<WorksndataItem> worksndataItems = new List<WorksndataItem>();

                        var sndata = new WorksndataItem()
                        {
                            sn = upload.serial_number
                        };
                        worksndataItems.Add(sndata);

                        List<WorkorderdatasItem> tempdatasItems = new List<WorkorderdatasItem>();
                        List<MaininfosItem> maininfosItems = new List<MaininfosItem>();
                        WorkorderdatasItem tempdatasItem = new WorkorderdatasItem();
                        tempdatasItem.disid = upload.disidno;
                        tempdatasItem.pono = upload.poid;
                        tempdatasItem.matid = upload.matid;
                        tempdatasItem.matdesc = upload.matdesc;
                        //tempdatasItem.workbatch = string.Empty;//批号
                        //tempdatasItem.worktype = string.Empty;//报工类型
                        //tempdatasItem.workerid = string.Empty;//报工人员
                        //tempdatasItem.workqty = "1";//报工数量
                        //tempdatasItem.laborhour = string.Empty;//工时
                        //tempdatasItem.workseq = upload.workbin;//工序
                        //tempdatasItem.workseqdesc = upload.workbinname;//工序描叙
                        //tempdatasItem.workseq_group = string.Empty;//工序组
                        //tempdatasItem.workseq_groupdesc = string.Empty;//工序组描叙
                        tempdatasItem.workbatch = "";//批号
                        tempdatasItem.worktype = "1";//报工类型
                        tempdatasItem.workerid = upload.operatorcode;//报工人员
                        tempdatasItem.workqty = "1";//报工数量
                        tempdatasItem.laborhour = "8";//工时
                        tempdatasItem.workseq = upload.workseq == null ? "" : upload.workseq; //工序
                        tempdatasItem.workseqdesc = upload.workseqdesc == null ? "" : upload.workseqdesc;//工序描叙
                        tempdatasItem.workseq_group = upload.disque;//工序组
                        tempdatasItem.workseq_groupdesc = upload.disque_desc;//工序组描叙
                        tempdatasItem.machinehour = "8";




                        tempdatasItem.worksndata = worksndataItems;
                        tempdatasItems.Add(tempdatasItem);
                        PlanData senddata = new PlanData() { workorderdatas = tempdatasItems };
                        bool sendResult = Send(senddata, upload.workbin);
                        if (sendResult == true)
                        {
                            //将工单状态改为“已报工”
                            //SubmitDB.UpdateWoInfoToFinish(upload);
                        }
                    }
                }
            }


            //var upload = smdc_disids.FirstOrDefault();
            ////_Disid_T = upload;
            //if (upload != null)
            //{
            //    List<WorksndataItem> worksndataItems = new List<WorksndataItem>();
            //    foreach (var item in smdc_disids)
            //    {
            //        var sndata = new WorksndataItem()
            //        {
            //            sn = item.serial_number
            //        };
            //        worksndataItems.Add(sndata);
            //    }
            //    List<WorkorderdatasItem> tempdatasItems = new List<WorkorderdatasItem>();
            //    List<MaininfosItem> maininfosItems = new List<MaininfosItem>();
            //    WorkorderdatasItem tempdatasItem = new WorkorderdatasItem();
            //    tempdatasItem.disid = upload.disidno;              
            //    tempdatasItem.po_no = upload.poid;
            //    tempdatasItem.matid = upload.matid;
            //    tempdatasItem.matdesc = upload.matdesc;
            //    tempdatasItem.workbatch = string.Empty;//批号
            //    tempdatasItem.worktype = string.Empty;//报工类型
            //    tempdatasItem.workerid = string.Empty;//报工人员
            //    tempdatasItem.workqty = string.Empty;//报工数量
            //    tempdatasItem.laborhour = string.Empty;//工时
            //    tempdatasItem.workseq = upload.workbin;//工序
            //    tempdatasItem.workseqdesc = upload.workbinname;//工序描叙
            //    tempdatasItem.workseq_group = string.Empty;//工序组
            //    tempdatasItem.workseq_groupdesc = string.Empty;//工序组描叙
            //    tempdatasItem.worksndata = worksndataItems;
            //    tempdatasItems.Add(tempdatasItem);
            //    PlanData senddata = new PlanData() { workorderdatas = tempdatasItems };
            //    bool sendResult= Send(senddata);
            //    if (sendResult == true) {
            //        //将工单状态改为“已报工”
            //        SubmitDB.UpdateWorkInfoToFinish(smdc_disids);
            //    }
            //}
        }

        //报工请求
        bool Send(PlanData senddata, string line)
        {
            var res = mqhelper.TopicExchangePublish(senddata, EXCHANAGE, "", $"{IfaceName}.{LineGroupName}"
                , true, false, true, false);
            if (res.Success)
            {
                System.Diagnostics.Debug.WriteLine("数据已推送完成的！");
                return true;
            }
            else 
            { 
                System.Diagnostics.Debug.WriteLine("数据推送失败！\n" + res.Message);
                return false;
            }
        }

        private void Loop()
        {
            var pgsql = new PgSqlAccess();
            using (var ctx = pgsql.GetClient())
            {
                if (pgsql.DBClient is SmdcOrmClient ormClient)
                {
                    var upload = ormClient.SqlSugarClient.Queryable<smdc_disid_t>().Where(m => m.state_int == (int)State.Finish).ToList();
                    CheckUpload(upload);
                }
            }
        }

        /// <summary>
        /// KJF 20210329 新增
        /// 手动报工
        /// </summary>
        public void PostWorkFinishReportByWorkID(string workID,string SN)
        {
            var pgsql = new PgSqlAccess();
            using (var ctx = pgsql.GetClient())
            {
                if (pgsql.DBClient is SmdcOrmClient ormClient)
                {
                    var upload = ormClient.SqlSugarClient.Queryable<smdc_disid_t>().Where(m => m.disidno== workID 
                    && m.serial_number==SN  && (m.state_int==(int)State.Finish || m.state_int == (int)State.UploadFinish)).ToList();
                    CheckUpload(upload);
                }
            }
        }

        public override void Start()
        {
            DataReceive();
            thread = new AdvancedThread(Loop, 30*60*1000);
            thread.Start();
        }

        public override void Stop()
        {
            thread.Stop();
            base.Stop();
        }

        void DataReceive()
        {
                //报工接口
                var res1 = mqhelper.TopicExchangeConsumer<BackResult>((data) =>
                {
                    if (data.retcode.Equals("1"))
                    {
                        SaveResult(data);
                        System.Diagnostics.Trace.WriteLine("配置结果接收成功");
                    }
                    return true;
                }, EXCHANAGE, $"ZEMT_MQ_SIE_{IfaceName}", $"{ROUTEKEY}.{LineGroupName}", true, false, true, false);
  

        }
        void SaveResult(BackResult WorkReportReceiveData) {

            if (WorkReportReceiveData!= null) {
                if (WorkReportReceiveData.retdatas !=null) {
                    foreach (var item in WorkReportReceiveData.retdatas) {
                        if (item.errormsg.Contains("报工成功")) {
                            SubmitDB.UpdateWoInfoToFinishByWorkNoAndSN(item.disid,item.worksn);
                        }
                    }
                }
            }

            Logger.Info("从MES收到报工应答消息！");
        }
        

        public class Retdatas
        {

            public string disid { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string matid { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string worksn { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string errormsg { get; set; }
        }

        public class BackResult
        {
            /// <summary>
            /// 
            /// </summary>
            public string retcode { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string retmsg { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public List<Retdatas> retdatas { get; set; }
        }

    }
}
